<?php
namespace Home\Controller;

use Think\Controller;

//TODO
//废弃确认
class UsersController extends CommonController
{
  protected $this_table = "users";

  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  //新建用户
  public function create()
  {
    $model = M($this->this_table);
    $now_time = gmtime();

    $post_data = I('post.');
    // $shop_id = $this->shop_id;
    $shop_id = trim(I('post.shop_id'));

    $nickname = trim(I('post.nickname'));
    $phone = trim(I('post.phone'));
    //加密方式--
    $passwd = trim(I('post.passwd', '123456'));
    //微信公众号和小程序
    $openid = trim(I('post.openid', ''));
    $xcx_openid = trim(I('post.xcx_openid', ''));

    $session3rd = trim(I('post.session3rd', ''));
    //获取xcx_openid
    if ($session3rd) {
      $sdata = S($session3rd);
      if ($sdata) {
        $xcx_openid = $sdata['openId'];
        //唯一性
        $find_user_id = M("users")->where("xcx_openid='".$xcx_openid."'")->getField("id");
        if ($find_user_id) {
          return_data("error", "users.xcx_openid.exist");
        } else {
          $post_data["xcx_openid"]=$xcx_openid;
        }
      }
    }

    //验证合法性
    if (!$nickname) {
      return_data("error", $this->this_table.".nickname.blank");
    }
    if (!$phone) {
      return_data("error", $this->this_table.".phone.blank");
    }
    if (!$passwd) {
      return_data("error", $this->this_table.".passwd.blank");
    }
    if (!$shop_id) {
      return_data("error", $this->this_table.".shop_id.blank");
    }

    //昵称
    $user_id = $model->where("nickname='".$nickname."'")->getField("id");
    if ($user_id) {
      return_data("error", $this->this_table.".nickname.exist");
    }

    //手机验证--唯一性--11位
    if (strlen($phone) != 11) {
      return_data("error", "create.phone.eleven.number");
    }
    if (!preg_match("/^1[0-9]{10}$/", $phone)) {
      return_data("error", "create.phone.error");
    }

    //手机唯一
    $user_id = M("users")->where("phone='".$phone."'")->getField("id");
    if ($user_id) {
      return_data("error", "users.phone.exist");
    }

    //openid唯一
    if ($openid) {
      $user_id = M("users")->where("openid='".$openid."'")->getField("id");
      if ($user_id) {
        return_data("error", "users.openid.exist");
      }
    }
    //xcx_openid
    // if($xcx_openid)
    // {
    //     $user_id = M("users")->where("xcx_openid='".$xcx_openid."'")->getField("id");
    //     if($user_id) return_data("error","users.xcx_openid.exist");
    // }

    //创建商铺
    $post_data["shop_id"] = $shop_id;

    $post_data["created_at"] = $now_time;
    $post_data["updated_at"] = $now_time;
    $post_data['types'] = 0;

    $salt = random(8);
    $post_data['salt'] = $salt;
    $post_data['passwd'] = md5(md5($passwd).$salt);

    $model->create($post_data);
    $user_id=$model->add();

    $token = D("users")->create_token($user_id);

    if ($user_id) {//$result!==false
      return_data("success", "create.shops.success", $token);
    } else {
      return_data("error", "create.shops.error");
    }
  }

  //获取用户信息
  public function show()
  {
    $id =$this->user_id;

    if (!$id) {
      return_data("error", $this->this_table.".id.blank");
    }

    //$where = "types=0 and shop_id=".$this->shop_id;
    $where = "1";
    $where .= " and id=".$id;
    $field = "*";
    $info = M("users")->field($field)->where($where)->find();

    if (empty($info)) {
      return_data("error", "show.users.empty");//blank
    } else {
      return_data("success", "show.users.success", $info);
    }
  }

  //获取用户户列表
  public function index()
  {
    $page_index = I("page_index", 1);
    $page_size = I("page_size", 10);
    //查询
    $nickname = I("nickname");
    //上架
    $where = "types=0 and shop_id=".$this->shop_id;
    if ($nickname) {//用户名
      $where .= " and nickname like '%".trim($nickname)."%'";
    }

    $field = "*";
    $order = "id desc";
    $list = M("users")->field($field)->where($where)->order($order)->page($page_index.",".$page_size)->select();

    if (empty($list)) {
      return_data("error", "index.users.empty");
    } else {
      return_data("success", "index.users.success", $list);
    }
  }

  //修改用户
  public function update()
  {
    $now_time = gmtime();
    $id = $this->user_id;
    $nickname= trim(I('post.nickname'));
    $phone = trim(I('post.phone'));
    //加密方式--
    $passwd = trim(I('post.passwd'));
    $openid = trim(I('post.openid'));
    $avatar = trim(I('post.avatar'));
    $session3rd = trim(I('post.session3rd', ''));

    //验证合法性
    if (!$nickname) {
      return_data("error", $this->this_table.".nickname.blank");
    }
    if (!$phone) {
      return_data("error", $this->this_table.".phone.blank");
    }

    //昵称验证-15位中文或数字--strlen只能是英文，中文需*3
    $post_data['nickname'] = $nickname;
    //手机验证--唯一性--11位
    if ($phone) {
      if (strlen($phone) != 11) {
        return_data("error", "update.phone.eleven.number");
      }
      if (!preg_match("/^1[0-9]{10}$/", $phone)) {
        return_data("error", "update.phone.error");
      }

      //手机唯一
      $user_id=M("users")->where("phone=".$phone)->getField("id");
      if ($user_id) {
        if ($user_id!=$this->user_id) {
          return_data("error", "users.phone.exist");
        }
      }

      $post_data['phone'] = $phone;
    }

    if ($passwd) {
      $salt = random(8);
      $post_data['salt'] = $salt;
      $post_data['passwd'] = md5(md5($passwd).$salt);
    }
    if ($openid) {
      $post_data['openid'] = $openid;
    }
    if ($avatar) {
      $post_data['avatar'] = $avatar;
    }

    //获取xcx_openid
    if ($session3rd) {
      $sdata = S($session3rd);
      if ($sdata) {
        $xcx_openid = $sdata['openId'];
        //唯一性
        $find_user_id = M("users")->where("id!=".$id." and xcx_openid='".$xcx_openid."'")->getField("id");
        if ($find_user_id) {
          return_data("error", "users.xcx_openid.exist");
        } else {
          $post_data["xcx_openid"]=$xcx_openid;
        }
      }
    }

    $model=M("users");
    $post_data["updated_at"] = $now_time;
    $where = "types in (0,1) and shop_id=".$this->shop_id;
    $where .= " and id=".$id;
    $result = $model->where($where)->save($post_data);
    if ($result) {//$result!==false
      return_data("success", "update.users.success");
    } else {
      return_data("error", "update.users.error");
    }
  }

  //获取手机号
  public function auth_phone()
  {
    Vendor("Wxapplet.wxBizDataCrypt");

    $payload = file_get_contents('php://input');
    $json = json_decode($payload);

    $iv = $json->iv;
    $encryptedData = $json->encryptedData;

    $session_key = M('users')->where("id={$this->user_id}")->getField('session_key');

    $app_info = $this->app_info;

    $pc = new \WXBizDataCrypt($app_info['cappid_applet'], $session_key);
    $err_code = $pc->decryptData($encryptedData, $iv, $data);

    // $data = json_decode($data, true);
    //return_data("success", "user.autu_phone.success", "{$err_code} -- {$data}");

    if ($err_code == 0) {
      $data = json_decode($data, true);

      $user['phone'] = $data['phoneNumber'];
      $user['updated_at'] = gmtime();
      $result = M('users')->where("id={$this->user_id}")->save($user);
      if ($result) {
        return_data("success", "user.auth_phone.success", $data['phoneNumber']);
      } else {
        return_data("error", "user.auth_phone.error", "{$err_code} -- {$data}");
      }
    } else {
      return_data("error", "auth_phone.encrypt_data.error", $err_code);
    }
  }

  public function history()
  {
    $where = "h.user_id={$this->user_id} and s.name IS NOT NULL";
    $field = "h.*, s.descrip, s.name, s.logo";
    $order = "updated_at desc";

    $list = M('history_logs')->alias('h')
          ->join("left join ".C("DB_PREFIX")."shops s on s.id=h.shop_id")
          ->where($where)
          ->field($field)
          ->order($order)
          ->group('shop_id')->limit(5)->select();

    foreach ($list as $key => &$info) {
      $info['updated_at'] = date("Y-m-d", $info['updated_at']);//local_time($info['created_at']);
      $info['descrip'] = mb_substr($info['descrip'], 0, 25, 'UTF8');
    }

    if ($list) {
      return_data("success", "index.history.success", $list);
    } else {
      return_data("error", "index.history.empty");
    }
  }
}
